package com.victor9ac.mashup.elasticsearch.converter;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import com.victor9ac.mashup.api.Comment;
import com.victor9ac.mashup.api.CommentSource;
import com.victor9ac.mashup.api.Commentaries;

public class ElasticSearchCommentConverter implements ElasticSearchConverter{

	final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

	
	/**
	 * object Domain to ES
	 */
	
	public List<XContentBuilder> buildJson(Object obj) 
			throws IOException {

		Commentaries commentaries = (Commentaries)obj;
		
		List<XContentBuilder> contentList = new ArrayList<XContentBuilder>();
		
		for(Comment comment:commentaries.getCommetaries()){
			contentList.add(buildContent(comment,commentaries.getKeywordLink()));
		}
		

		return contentList;
	}
	

	XContentBuilder buildContent(Comment comment,String keyword) throws IOException {
		XContentBuilder json = jsonBuilder()
				.startObject()
				.field("keyword", keyword.toUpperCase())
				.field("author", comment.getAuthor())
				.field("comment", comment.getText())
				.field("commentDate", comment.getCommentDate())
				.field("source", comment.getSource().name())
				.field("dataDate", new Date())
				.endObject();
		return json;
	}
	
	
	/**
	 * parse ES to Domain
	 */
	
	public Object convert(SearchResponse searchResponse) throws ParseException{
		Commentaries commentaries = null;
		if (hasResults(searchResponse)){
			commentaries = new Commentaries();
			SearchHits hits = searchResponse.getHits();
			for (SearchHit searchHit : hits) {
				String author = (String)searchHit.getSource().get("author");
				String comment = (String)searchHit.getSource().get("comment");
				String keywordES = (String)searchHit.getSource().get("keyword");
				
				Calendar commentDate = Calendar.getInstance();
				commentDate.setTime(sdf.parse((String) searchHit.getSource().get("commentDate")));
				
				String source = (String)searchHit.getSource().get("source");
				
				//FIX
				CommentSource commentSrc = source.equals(CommentSource.TWITTER.name()) ? commentSrc = CommentSource.TWITTER : CommentSource.UNDEF;
				
				Comment c = new Comment(author, comment, commentDate.getTime(), commentSrc);
				commentaries.add(c);
				commentaries.setKeywordLink(keywordES);
			}
		}
		return commentaries;

	}
	
	private boolean hasResults(SearchResponse searchResponse){
		SearchHits hits = searchResponse.getHits();
		
		return  hits.getTotalHits() > 0;
		
	}


}
